package me.feng.actors

import akka.actor.Actor
import scala.collection.mutable.Map
import me.feng.OschartContext
import akka.actor.Props
import me.feng.entity.Event
import me.feng.entity.EventType
import me.feng.entity.User
import scala.collection.mutable.Map
import akka.actor.Kill
import me.feng.entity.Message
import me.feng.entity.Letter
import me.feng.entity.Letter
import me.feng.entity.LetterType
import me.feng.messageinbound.MainChart
import akka.actor.ActorRef

class MainActor extends Actor {

  val olUserMap = Map[String, User]()

  def receive = {
    case msg: Message[Letter] => {
      val letter = msg.result.asInstanceOf[Letter]
      val cid = letter.cid
      letter.kind match {
        case LetterType.USER => {
          val userActor = context.actorFor(cid)
          val selfActor = context.actorFor(letter.from.id)
          userActor ! msg
          selfActor ! msg
        }

        case LetterType.MAIN => {
          context.children.foreach(ac => {
            ac ! msg
          })
        }

        
      }

    }

    case p: (String, MainChart) => {

      olUserMap.foreach(p => {
        println("olUserMap: " + p._1 + " -> " + p._2.id)
      })

      var newActor = false
      val userActor = if (!context.child(p._1).isDefined) {
        newActor = true
        println("uid 登陆：" + p._2.getUser.id)
        println("new actor:" + p._2.getUser.id)
        context.actorOf(Props(classOf[UserActor], p._2.getUser), p._2.getUser.id)
      } else
        context.child(p._1).get
      userActor ! p._2
      if (newActor) {
        olUserMap += (p._2.getUser.id -> p._2.getUser)
        context.children.filter(ac => {
          !ac.path.name.equals(p._2.getUser.id)
        }).foreach(a => {
          a ! new Event(p._2.getUser, MainActor.DEFAULT_MAIN_ID, EventType.LOGIN)
        })
        userActor ! olUserMap
      }
    }

    case e: Event => {

      e.event match {
        case EventType.CLOSE => {
          olUserMap.remove(e.u.id)
          context.children.filter(a => {
            a.path.name.equals(e.u.id)
          }).foreach(ac => {
            println("Kill===" + ac)
            context.system.stop(ac)
          })
          context.children.foreach(a => {
            a ! e
          })
        }
        case EventType.NEW_SESSION =>{
          context.actorFor(e.cid) ! e
        }
        case _ =>
      }

    }
  }
}

object MainActor {
  val DEFAULT_MAIN_ID = "0"
}